package com.cn.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // ServletRequest 类型的 requset 对象没有获取 session 对象的方法
        // 所以此时需要将 request对象强转成 `HttpServletRequest` 对象。
        HttpServletRequest req = (HttpServletRequest)servletRequest;

        //判断访问资源路径是否和登录注册相关
        //1.在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};
        //2.获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        //3.遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {
            //判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
            //比如当前访问的资源路径是  /brand-demo/login.jsp
            //而字符串 /brand-demo/login.jsp 包含了  字符串 /login.jsp ，所以这个字符串就需要放行
            if(url.contains(u)){
                //找到了，放行
                filterChain.doFilter(servletRequest, servletResponse);
                //找到了，放行，回来不用访问下面的代码了
                return;
            }
        }
        System.out.println("hh");

        //1.判断session中是否有user
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");

        //2.判断user是否为null
        if(user != null){
            //说明登录过了，放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //没有登录，存储提示信息，跳转到登录页面
            req.setAttribute("login_msg","您尚未登录");
            req.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        }


    }

    @Override
    public void destroy() {

    }
}
